package com.xiaojie.config;

import com.xiaojie.entity.Permission;
import com.xiaojie.filter.JWTLoginFilter;
import com.xiaojie.filter.JWTValidationFilter;
import com.xiaojie.mapper.PermissionMapper;
import com.xiaojie.service.LimitLoginAuthenticationProvider;
import com.xiaojie.service.UserService;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;

/* *
 * @Author yan
 * @Description //TODO
 * @Date 2021/4/28 2021/4/28
 * @Param
 * @return
 **/
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Reference
    private UserService userService;
    @Reference
    private PermissionMapper permissionMapper;
    @Autowired
    private LimitLoginAuthenticationProvider limitLoginAuthenticationProvider;

    @Override
 /* *
  * @Author yan
  * @Description //TODO
  * @Date 2021/4/28 9:16
  * @Param [auth]
  * @return void
  **/
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //密码验证次数
        auth.authenticationProvider(limitLoginAuthenticationProvider);
        auth.userDetailsService(userService).passwordEncoder(new PasswordEncoder() {
            @Override
           /* public String encode(CharSequence charSequence) {
                return (String) charSequence;
            }*/
            public String encode(CharSequence charSequence) {
                return DigestUtils.md5Hex((String)charSequence);
            }
            @Override
            public boolean matches(CharSequence charSequence, String s) {
                if (StringUtils.isNotEmpty(charSequence)){
                    return DigestUtils.md5Hex((String)charSequence).equals(s);
                }
                return false;
            }
        });
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        List<Permission> permissions = permissionMapper.findAll();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry
                expressionInterceptUrlRegistry = http.authorizeRequests();
        permissions.forEach(permission -> {
            expressionInterceptUrlRegistry.antMatchers(permission.getUrl())
                    .hasAnyAuthority(permission.getPermTag());
        });
        /*expressionInterceptUrlRegistry.antMatchers("/login").permitAll()
                .antMatchers("/**")
                .fullyAuthenticated().and().formLogin().loginPage("/login")
                .and().csrf().disable();*/
        //设置过滤器
        expressionInterceptUrlRegistry.antMatchers("/login").permitAll()
                .antMatchers("/**").fullyAuthenticated()
                .and()
                // 设置过滤器
                .addFilter(new JWTValidationFilter(authenticationManager()))
                .addFilter(new JWTLoginFilter(authenticationManager())).csrf().disable()
                //剔除session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
